﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using ClassLibrary;

namespace LVTN
{
    public partial class Form1 : Form
    {
        int id = 0;
        string timeresult;
        DateTime t2;
        Boolean serverFinish = false;//reset = false
        int tongThread;//ko can
        double[,] A;
        double[,] B;
        double[,] C;
        int N;
        int[] stateLst = new int[20];// =0
        MemoryStream tempStream = new MemoryStream();// set position 0 when refesh
        Boolean checkDataTimeReceive = false;
        class Params
        {
            public int sr;
            public int er;
            public int id;
            public Params(int s, int e, int i)
            {
                sr = s;
                er = e;
                id = i;
            }
        };

     //   MemoryStream teapm
        Boolean startcal = false;
        Socket server;
        IPEndPoint ipe;
        //int BUFERSIZE = 1024 * 1024 * 100;

        class ServerState
        {
            public byte[] Buffer = new byte[1024*1024*10]; //buffer for network i/o
            public int DataSize = 0; //data size to be received by the server
            public bool DataSizeReceived = false; //whether prefix was received
            public MemoryStream Data = new MemoryStream(); //place where data is stored
            public Socket Client;   //client socket
            public int index=0;
        };

        public class ClientState
        {
            public Socket Client; //client socket
            public byte[] DataToSend; //data to be trasferred
            public int DataSent = 0; //data already sent
            public int index;
        }
        public List<myStruct> lstClient = new List<myStruct>();
        public List<System.TimeSpan> timeListCalculateServer= new List<System.TimeSpan>();
        String myIP = "";
        Thread handlerCLient;
        Thread checkFinishProcess;
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            lbResult.Items.Clear();
            N = 2000;
            A = new double[N, N];
            B = new double[N, N];
            C = new double[N, N];
            int h, c;
            for (h = 0; h < N; h++)
                for (c = 0; c < N; c++)
                    A[h, c] = B[h, c] = c;
            for (h = 0; h < 4; h++) stateLst[h] = 0;
            listView1.View = View.Details;
        }

       
        public void getIP()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress address in host.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    myIP = address.ToString();
                }
            }
            ipe = new IPEndPoint(IPAddress.Parse(myIP), 2013);
            server= new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.IP);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            getIP();
            handlerCLient = new Thread(new ThreadStart(Listening));
            handlerCLient.IsBackground = true;
            handlerCLient.Start();            
        }
        public void Listening()
        {
            server.Bind(ipe);
            server.Listen(10);
            while (true)
            {
                myStruct client = new myStruct();
                client.id = id;
                client.Count = 0;
                client.Data = A;
                client.Matrixsize = N;
                client.Status = 1;
                client.datareceiving = false;
                client.checkTime = false;
                client.MySocket= server.Accept();
                client.checkTimeReceiveData = 0;
                client.checkDataResultReceive = false;
                lstClient.Add(client);
                id = id + 1;
              //  ServerState state = new ServerState();//
            //    state.Client = client.MySocket;
                //issue first receive
             //     client.MySocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ServerReadCallback), state);

                Thread myClientProcess = new Thread(MyClientProcess);
                myClientProcess.IsBackground = true;
                myClientProcess.Start(client);
            }

        }

        public void MyClientProcess(object obj)
        {
            myStruct objectClient = (myStruct)obj;
            Socket clientSK = objectClient.MySocket;
            //byte[] buff = new byte[BUFERSIZE];
            ServerState state = new ServerState();//
            state.Client = clientSK;
            int index = 0;
            for (int i = 0; i < lstClient.Count(); i++)
            {
                if (lstClient[i].MySocket == state.Client)
                {
                    index = i;
                }
            }
            while (true)
            {
                while (lstClient[index].datareceiving)
                {

                }
                //   int recieve = clientSK.Receive(buff);
                //    issue first receive
               // state.DataSizeReceived
                state.DataSizeReceived = false;
                state.DataSize = 0;
                if (lstClient[index].checkDataResultReceive == true)
                {
                    state.Data = tempStream;
                    state.DataSize = lstClient[index].DataSizeRecive;
                    state.DataSizeReceived = lstClient[index].checkDataSizeReceived;
                }
                else
                { 
                   state.Data =new MemoryStream();
                }
                while (clientSK.Available == 0)
                { 
                }

                lstClient[index].datareceiving = true;
                if (lstClient[index].checkTimeReceiveData == 1)
                {
                    lstClient[index].timeServerStartReadData = DateTime.Now;
                }
                    clientSK.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ServerReadCallback), state);

                /*   myStruct data = MaHoa(buff);
                   int index = 0;
                   for (int i = 0; i < lstClient.Count(); i++)
                   {
                       if (lstClient[i].MySocket == clientSK)
                       {
                           index = i;
                       }
                   }
                   if (data.Count == 0)// do not calculator
                   {
                       lstClient[index].Thread = data.Thread;
                       //show data len table
                       lbResult.Items.Add(String.Format("Client {0:d} is connecting ", lstClient[index].MySocket.RemoteEndPoint.ToString()));
                       ListViewItem lst = new ListViewItem();
                       lst.Text = "";
                       lst.SubItems.Add(index.ToString());
                       lst.SubItems.Add(lstClient[index].MySocket.RemoteEndPoint.ToString());
                       lst.SubItems.Add(lstClient[index].Thread.ToString());
                       listView1.Items.Add(lst);

                       //wait for click button start
                       while (!startcal)
                       {
                       }

                       // Serialize sending data 
                       if (lstClient[index].Ischecked == 1)
                       {
                        
                           MemoryStream stream = new MemoryStream();
                           BinaryFormatter bformat = new BinaryFormatter();
                           bformat.Serialize(stream, lstClient[index]);
                           buff = stream.ToArray();//convert to bytes
                           lstClient[index].MySocket.Send(buff);//send data to client
                       }
                   }
                   else if (data.Count == 1)
                   {
                       int h, c;
                       for (h = data.Sr; h < data.Er; h++)
                           for (c = 0; c < N; c++)
                           {
                               C[h, c] = data.Data[h, c];
                           }
                       lstClient[index].Count = 1;// finish calculator
                       lstClient[index].Status = 1;
                   }
               }*/
            }
        }

        private myStruct MaHoa(byte[] buff)
        {
            MemoryStream stream = new MemoryStream(buff);
            BinaryFormatter bformat = new BinaryFormatter();
            myStruct data = (myStruct)bformat.Deserialize(stream);
            return data;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //set up operating data for server
            this.btnStart.Enabled = false;
            int cnt;
            int buocnhay = 0;
            for (int i = 0; i < lstClient.Count; i++)
            {
                lstClient[i].Status = 1;
            }
            if (txtThread.Text == "")
            {
                cnt = 0;
            }
            else
            {
                cnt = Int32.Parse(txtThread.Text);
            }
            tongThread = cnt;
            ListView.CheckedListViewItemCollection checkedItems = listView1.CheckedItems;
            if (checkedItems != null)
            {
                foreach (ListViewItem item in checkedItems)
                {
                    tongThread = tongThread + Int32.Parse(item.SubItems[3].Text);
                }

                // setup data to send to client
                for (int i = 0; i < checkedItems.Count; i++)
                {
                    int index = 0;

                    for (int j = 0; j < lstClient.Count(); j++)
                    {
                       // if (lstClient[j].MySocket.Connected)
                     //   { };
                     
                        if (lstClient[j].MySocket.RemoteEndPoint.ToString() == (checkedItems[i].SubItems[2].Text))
                        {
                            index = j;
                            lstClient[index].Matrixsize = N;
                            lstClient[index].Data = A;
                            lstClient[index].Sr = buocnhay * N / tongThread;
                            lstClient[index].Er = (buocnhay + lstClient[index].Thread) * N / tongThread;
                            buocnhay = buocnhay + lstClient[index].Thread;
                            lstClient[index].Status = 0;
                            lstClient[index].ischecked = 1;
                           
                        }
                    }
                }
            }

            if (tongThread == 0)// inform to correct control
            {

            }
            else //start calculator
            {
                //get time start
                DateTime t1 = DateTime.Now;
                 checkFinishProcess = new Thread( new ParameterizedThreadStart(myCheckFinishProcess));
               checkFinishProcess.IsBackground = true;
                checkFinishProcess.Start(t1);
                // start calculator
                startcal = true;

                // server's cpus calculator
                int str = buocnhay * N / tongThread;
                int enr = N;
                int sd = enr - str + 1;
                if (cnt == 1) //synchronous
                {
                    TinhTich(new Params(str, enr, 0));
                    serverFinish = true;
                }
                else //asynchoronous
                {
                    int i;
                    Thread t;
                    for (i = 0; i < cnt - 1; i++)
                    {
                        stateLst[i] = 0;
                        t = new Thread(new ParameterizedThreadStart(TinhTich));
                        t.Start(new Params(str + i * sd / cnt, str + (i + 1) * sd / cnt, i));
                    }
                    TinhTich(new Params(str + (cnt - 1) * sd / cnt, enr, cnt - 1));
                    for (i = 0; i < cnt - 1; i++)
                        while (stateLst[i] == 0) //wait for server's cpus
                            {

                            };
                    serverFinish = true;
                }
            }
        }
        void TinhTich(object obj)
        {
            DateTime timeStartCalculate = DateTime.Now;
            Params p = (Params)obj;
           int h, c, k;
            for (h = p.sr; h < p.er; h++)
                for (c = 0; c < N; c++)
                {
                    double s = 0;
                    for (k = 0; k < N; k++)
                        s = s + A[h, k] * B[k, c];
                    C[h, c] = s;
                }
           
            stateLst[p.id] = 1;
            DateTime timeEndCalculate = DateTime.Now;
            System.TimeSpan timediff = timeEndCalculate.Subtract(timeStartCalculate);
            timeListCalculateServer.Add(timediff);
            lbResult.Items.Add(String.Format(" thoi gian server tinh {0:d2} phut {1:d2} giay {2:d3} ms", timediff.Minutes, timediff.Seconds, timediff.Milliseconds));
        }

        private void ServerReadCallback(IAsyncResult ar)
        {
            ServerState state = (ServerState)ar.AsyncState;
            Socket client = state.Client;
            SocketError socketError;

            int dataRead = client.EndReceive(ar, out socketError);
            int tempRead = dataRead;
            int dataOffset = 0; //to simplify logic

            if (socketError != SocketError.Success)
            {
                client.Close();
                return;
            }

            if (dataRead <= 0)
            { //connection reset 
                client.Close();
                return;
            }

            if (!state.DataSizeReceived)
            {
                if (dataRead >= 4)
                {   //we received data size prefix
                    state.DataSize = BitConverter.ToInt32(state.Buffer, 0);
                    state.DataSizeReceived = true;
                    dataRead -= 4;
                    dataOffset += 4;
                }
            }
           if (state.DataSizeReceived == true)
            {
                if (state.Data.Length + dataRead > state.DataSize)
                {
                    int tempDataSize = 0;
                    int tempDataRead =(int)(state.Data.Length + dataRead -state.DataSize);
                    int tempOffsetSize = tempRead - tempDataRead;
                    if (tempDataRead >= 4)
                    {
                        tempDataSize = BitConverter.ToInt32(state.Buffer, tempOffsetSize);
                        tempDataRead -= 4;
                        tempOffsetSize += 4;
                        tempStream.Write(state.Buffer, tempOffsetSize, tempDataRead);
                       // lbResult.Items.Add(String.Format("Data received.thua thuc te Size: {0:d} ", tempDataRead));
                       // lbResult.Items.Add(String.Format("Data received.thua ly thuyet: {0:d} ", tempDataSize));
                        int index = 0;
                        for (int i = 0; i < lstClient.Count(); i++)
                        {
                            if (lstClient[i].MySocket == state.Client)
                            {
                                index = i;
                            }
                        }
                        if (tempDataRead == tempDataSize)
                        {
                            myStruct tempData = MaHoa(tempStream.ToArray());
                           
                            lstClient[index].timeSpanClientSendData = tempData.timeSpanClientSendData;
                            lstClient[index].timeSpanClientReadData = tempData.timeSpanClientReadData;
                            lstClient[index].timeClientCalculate = tempData.timeClientCalculate;
                            lstClient[index].checkTime = true;
                            tempStream.Position = 0;
                        }
                        else
                        {
                            lstClient[index].checkDataResultReceive = true;
                            lstClient[index].checkDataSizeReceived = true;
                            lstClient[index].DataSizeRecive = tempDataSize;
                        }
                        dataRead=dataRead-tempDataRead -4;
                    }
                }
 
            }
            if ((state.Data.Length + dataRead) == state.DataSize)
            {   //we have all the data
            
                state.Data.Write(state.Buffer, dataOffset, dataRead);

                lbResult.Items.Add(String.Format("Data received"));
                myStruct data = MaHoa(state.Data.ToArray());
                int index = 0;
                for (int i = 0; i < lstClient.Count(); i++)
                {
                    if (lstClient[i].MySocket == state.Client)
                    {
                        index = i;
                    }
                }
                if (lstClient[index].checkTimeReceiveData == 1)
                {
                    DateTime timeReceiveData = DateTime.Now;
                    lstClient[index].timeSpanServerReadData = timeReceiveData.Subtract(lstClient[index].timeServerStartReadData);
                }
                lstClient[index].checkTimeReceiveData = lstClient[index].checkTimeReceiveData+1;
                lstClient[index].datareceiving = false;
                if (data.Count == 0)// do not calculator
                {
                    lstClient[index].Thread = data.Thread;
                    //show data len table
                    lbResult.Items.Add(String.Format("Client {0:d} is connecting ", lstClient[index].MySocket.RemoteEndPoint.ToString()));
                    //        lbResult.Items.Add(String.Format("Client {0:d} is connecting ", lstClient[index].MySocket.RemoteEndPoint.ToString()));
                    ListViewItem lst = new ListViewItem();
                    lst.Text = "";
                    lst.SubItems.Add(lstClient[index].id.ToString());
                    lst.SubItems.Add(lstClient[index].MySocket.RemoteEndPoint.ToString());
                    lst.SubItems.Add(lstClient[index].Thread.ToString());
                    listView1.Items.Add(lst);

                    //wait for click button start
                    while (!startcal)
                    {
                    }

                    // Serialize sending data 
                    if (lstClient[index].ischecked == 1)
                    {

                        MemoryStream stream = new MemoryStream();
                        BinaryFormatter bformat = new BinaryFormatter();
                        bformat.Serialize(stream, lstClient[index]);
                        // lstClient[index].MySocket.Send(buff);//send data to client
                        ClientState state1 = new ClientState();
                        state1.Client = lstClient[index].MySocket;
                        state1.index = index;
                        //add prefix to data
                        Byte[] data1 = stream.ToArray();
                        state1.DataToSend = new byte[data1.Length + 4];
                        byte[] prefix = BitConverter.GetBytes(data1.Length);
                        //copy data size prefix
                        Buffer.BlockCopy(prefix, 0, state1.DataToSend, 0, prefix.Length);
                        //copy the data
                        Buffer.BlockCopy(data1, 0, state1.DataToSend, prefix.Length, data1.Length);
                        lstClient[index].timeServerStartSendData = DateTime.Now;
                        lstClient[index].MySocket.BeginSend(state1.DataToSend, 0, state1.DataToSend.Length,
                          SocketFlags.None, new AsyncCallback(ClientSendCallback), state1);
                        //  lstClient[index].Status = 1;        
                    }
                }
                else if (data.Count == 1)
                {
                    DateTime timeCopyDataStart = DateTime.Now;
                    int h, c;
                    for (h = data.Sr; h < data.Er; h++)
                        for (c = 0; c < N; c++)
                        {
                            C[h, c] = data.Data[h, c];
                        }
                    DateTime timeCopyDataEnd = DateTime.Now;
                    lstClient[index].Count = 1;// finish calculator
                    lstClient[index].Status = 1;

                    lstClient[index].timeSpanCopyResult = timeCopyDataEnd.Subtract(timeCopyDataStart);
                    lbResult.Items.Add(String.Format(" thoi gian sao luu du lieu {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[index].timeSpanCopyResult.Minutes, lstClient[index].timeSpanCopyResult.Seconds, lstClient[index].timeSpanCopyResult.Milliseconds));

                    /*   for (int i = 0; i < lstClient.Count; i++)
                           while (lstClient[i].Status == 0) { }; //wait for all client finish calculating

                       //get time finish
                      t2 = DateTime.Now;
                       System.TimeSpan diff = t2.Subtract(t1);

                       //show result
                       lbResult.Items.Add(String.Format("{0:d} threads ==> Thoi gian chay la {1:d2} phut {2:d2} giay {3:d3} ms", tongThread, diff.Minutes, diff.Seconds, diff.Milliseconds));*/
                }
                else if (data.Count == 2)
                {
                    lstClient[index].timeSpanClientSendData = data.timeSpanClientSendData;
                    lstClient[index].timeSpanClientReadData = data.timeSpanClientReadData;
                    lstClient[index].timeClientCalculate = data.timeClientCalculate;
                    lstClient[index].checkTime = true; 

                }
                //     client.Close();
                // return;
            }
            else
            {   //there is still data pending, store what we've
                //received and issue another BeginReceive
                state.Data.Write(state.Buffer, dataOffset, dataRead);

                client.BeginReceive(state.Buffer, 0, state.Buffer.Length,
                  SocketFlags.None, new AsyncCallback(ServerReadCallback), state);
            }
        }


        private void ClientSendCallback(IAsyncResult ar)
        {

            ClientState state = (ClientState)ar.AsyncState;
            
            
            SocketError socketError;
            int sentData = state.Client.EndSend(ar, out socketError);
          
            if (socketError != SocketError.Success)
            {
                state.Client.Close();
                return;
            }

            state.DataSent += sentData;

            if (state.DataSent != state.DataToSend.Length)
            {   //not all data was sent
                state.Client.BeginSend(state.DataToSend, state.DataSent,
                  state.DataToSend.Length - state.DataSent, SocketFlags.None,
                    new AsyncCallback(ClientSendCallback), state);
            }
            else
            {   //all data was sent
                //Console.WriteLine("All data was sent. Size: {0}",state.DataToSend.Length);
                DateTime t3 = DateTime.Now;
                lstClient[state.index].timeSpanServerSendData = t3.Subtract(lstClient[state.index].timeServerStartSendData);
               lbResult.Items.Add(String.Format("All data was sent. Size: {0} ", state.DataToSend.Length));
               //  lbResult.Items.Add(String.Format("All data was sent. Size:  "));
              
               // state.Client.Close();
                //lbResult.Items.Add(String.Format("Client {0:d} is connecting ", lstClient[0].MySocket.RemoteEndPoint.ToString()));
            }
        }
        public void myCheckFinishProcess(object obj)
        {
            DateTime t1 = (DateTime)obj;
            
            for (int i = 0; i < lstClient.Count; i++)
                while (lstClient[i].Status == 0) { }; //wait for all client finish calculating
            while (serverFinish == false)
            {

            };
            //get time finish
            t2 = DateTime.Now;
            System.TimeSpan diff = t2.Subtract(t1);

            //show result
            lbResult.Items.Add(String.Format("{0:d} threads ==> Thoi gian chay la {1:d2} phut {2:d2} giay {3:d3} ms", tongThread, diff.Minutes, diff.Seconds, diff.Milliseconds));
            timeresult =String.Format("{0:d} threads ==> Thoi gian chay la {1:d2} phut {2:d2} giay {3:d3} ms", tongThread, diff.Minutes, diff.Seconds, diff.Milliseconds);
            this.btnStart.Enabled = true;
            for (int i = 0; i < lstClient.Count; i++)
            {
                if (lstClient[i].ischecked == 1)
                {
                    while (lstClient[i].checkTime ==false ) { };
                }
            }
            ListView.CheckedListViewItemCollection checkedItems = listView1.CheckedItems;
            if (checkedItems != null)
            {
                using (var writer = new StreamWriter("result.txt"))
                {

                    // Write format string to file
                   // writer.Write("{0:0.0} ", i);

                    // setup data to send to client
                    for (int h = 0; h < timeListCalculateServer.Count(); h++)
                    {
                        //lbResult.Items.Add(String.Format("thoi gian server tinh toan {0:d2} phut {1:d2} giay {2:d3} ms", timeListCalculateServer[h].Minutes, timeListCalculateServer[h].Seconds, timeListCalculateServer[h].Milliseconds));
                        writer.WriteLine("{0:d}", String.Format("  thoi gian server tinh toan {0:d2} phut {1:d2} giay {2:d3} ms", timeListCalculateServer[h].Minutes, timeListCalculateServer[h].Seconds, timeListCalculateServer[h].Milliseconds));
                    }
                    writer.WriteLine("-------------------------------------------------------");
                    for (int i = 0; i < checkedItems.Count; i++)
                    {
                        //int index = 0;

                        for (int j = 0; j < lstClient.Count(); j++)
                        {
                            if (lstClient[j].MySocket.RemoteEndPoint.ToString() == (checkedItems[i].SubItems[2].Text))
                            {
                               // lbResult.Items.Add(String.Format("{0:d} thoi gian server send data {1:d2} phut {2:d2} giay {3:d3} ms", lstClient[j].MySocket.RemoteEndPoint.ToString(), lstClient[j].timeSpanServerSendData.Minutes, lstClient[j].timeSpanServerSendData.Seconds, lstClient[j].timeSpanServerSendData.Milliseconds));
                                //lbResult.Items.Add(String.Format("{0:d} thoi gian client read data {1:d2} phut {2:d2} giay {3:d3} ms", lstClient[j].MySocket.RemoteEndPoint.ToString(), lstClient[j].timeSpanClientReadData.Minutes, lstClient[j].timeSpanClientReadData.Seconds, lstClient[j].timeSpanClientReadData.Milliseconds));
                                writer.WriteLine("{0:d}", lstClient[j].MySocket.RemoteEndPoint.ToString());
                                writer.WriteLine("{0:d}", String.Format(" thoi gian server send data {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeSpanServerSendData.Minutes, lstClient[j].timeSpanServerSendData.Seconds, lstClient[j].timeSpanServerSendData.Milliseconds));
                                writer.WriteLine("{0:d}", String.Format("  thoi gian client read data {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeSpanClientReadData.Minutes, lstClient[j].timeSpanClientReadData.Seconds, lstClient[j].timeSpanClientReadData.Milliseconds));
                                for (int h = 0; h < lstClient[j].timeClientCalculate.Count(); h++)
                                {
                                   // lbResult.Items.Add(String.Format("thoi gian client tinh toan {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeClientCalculate[h].Minutes, lstClient[j].timeClientCalculate[h].Seconds, lstClient[j].timeClientCalculate[h].Milliseconds));
                                    writer.WriteLine("{0:d}",String.Format("   thoi gian client tinh toan {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeClientCalculate[h].Minutes, lstClient[j].timeClientCalculate[h].Seconds, lstClient[j].timeClientCalculate[h].Milliseconds));
                                }
                                  //  lbResult.Items.Add(String.Format("{0:d} thoi gian client send data {1:d2} phut {2:d2} giay {3:d3} ms", lstClient[j].MySocket.RemoteEndPoint.ToString(), lstClient[j].timeSpanClientSendData.Minutes, lstClient[j].timeSpanClientSendData.Seconds, lstClient[j].timeSpanClientSendData.Milliseconds));
                              //  lbResult.Items.Add(String.Format("{0:d} thoi gian server read data {1:d2} phut {2:d2} giay {3:d3} ms", lstClient[j].MySocket.RemoteEndPoint.ToString(), lstClient[j].timeSpanServerReadData.Minutes, lstClient[j].timeSpanServerReadData.Seconds, lstClient[j].timeSpanServerReadData.Milliseconds));
                              //  lbResult.Items.Add(String.Format(" thoi gian sao luu du lieu {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeSpanCopyResult.Minutes, lstClient[j].timeSpanCopyResult.Seconds, lstClient[j].timeSpanCopyResult.Milliseconds));
                               // lbResult.Items.Add(timeresult);
                                
                                writer.WriteLine("{0:d}", String.Format("    thoi gian client send data {0:d2} phut {1:d2} giay {2:d3} ms",  lstClient[j].timeSpanClientSendData.Minutes, lstClient[j].timeSpanClientSendData.Seconds, lstClient[j].timeSpanClientSendData.Milliseconds));
                                writer.WriteLine("{0:d}", String.Format("     thoi gian server read data {0:d2} phut {1:d2} giay {2:d3} ms",  lstClient[j].timeSpanServerReadData.Minutes, lstClient[j].timeSpanServerReadData.Seconds, lstClient[j].timeSpanServerReadData.Milliseconds));
                                writer.WriteLine("{0:d}", String.Format("      thoi gian sao luu du lieu {0:d2} phut {1:d2} giay {2:d3} ms", lstClient[j].timeSpanCopyResult.Minutes, lstClient[j].timeSpanCopyResult.Seconds, lstClient[j].timeSpanCopyResult.Milliseconds));
                                writer.WriteLine("-------------------------------------------------------");
                            }
                        }
                    }
                    writer.WriteLine("{0:d}", timeresult);
                }
            }
        }

        private void btnRefesh_Click(object sender, EventArgs e)
        {
             List<int> arrayStore = new List<int>();
             for (int j = 0; j < lstClient.Count; j++)
            {
               for (int i = listView1.Items.Count-1; i>=0;i-- )
                {
                    if (lstClient[j].id.ToString() == listView1.Items[i].SubItems[1].Text)
                    {
                        if (!lstClient[j].MySocket.Connected)
                        {//disconnect clear 

                            arrayStore.Add(lstClient[j].id);
                            listView1.Items[i].Remove();
                        }
                    }
                }
            }
             /*for (int j = 0; j < arrayStore.Count; j++)
             {
                 for (int i = lstClient.Count - 1; i >= 0; i--)
                 {
                     if (arrayStore[j] == lstClient[i].id)
                     {
                         lstClient.Remove(lstClient[i]);
                     }
                 }
             }
              * */
        }
    }
}
